package com.example.ioc.controller;

import com.alibaba.fastjson.JSON;
import com.example.ioc.pojo.Result;
import com.example.ioc.service.TransferService;
import com.example.spring.framework.annotation.Autowired;
import com.example.spring.framework.annotation.Controller;
import com.example.spring.framework.annotation.RequestMapping;
import com.example.spring.framework.annotation.RequestParam;
import com.example.spring.framework.webmvc.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：wuhong-016
 * @version v1.0.0
 * @Create : 2021/1/18 15:51
 * @Description : TODO
 **/
@Controller
@RequestMapping("/transfer")
public class TransferController {

    @Autowired
    private TransferService transferService;

    @RequestMapping("/index.view")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("page/index");
    }

    /**
     * 参数类型转换问题先搁置
     * request 中取到的money是string，此处RequestParam如果是int会报错：参数不匹配
     * java.lang.IllegalArgumentException: argument type mismatch
     * at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     * at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
     * at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     * at java.base/java.lang.reflect.Method.invoke(Method.java:564)
     * <p>
     * remark：先忽略类型转换的细节  money设置成string 手动转换
     *
     * @param request
     * @param response
     * @param fromCardNo
     * @param toCardNo
     * @param money
     */
    @RequestMapping("/doTransfer.json")
    public void doTransfer(HttpServletRequest request, HttpServletResponse response, @RequestParam("fromCardNo") String fromCardNo, @RequestParam("toCardNo") String toCardNo, @RequestParam("money") String money) {


        Result result = new Result();

        try {
            // 2. 调用service层方法
            int moneyInt = Integer.parseInt(money);
            transferService.transfer(fromCardNo, toCardNo, moneyInt);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        this.out(response, JSON.toJSONString(result));
    }

    private void out(HttpServletResponse response, String str) {
        try {
            response.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
